package servlet;

import dao.CategoryDao;
import dao.daoimpl.CategoryDaoImpl;
import bean.Category;
import bean.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(name="AddCategoryServlet",urlPatterns = "/AddCategoryServlet")
public class AddCategoryServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");/*防止乱码*/
        User user=(User)request.getSession().getAttribute("user");
        String name=request.getParameter("addArticleCategoryName");/*获取目录名称*/
        String intro=request.getParameter("addArticleCategoryIntro");/*获取目录简介*/
        CategoryDao categoryDao=new CategoryDaoImpl();/*目录接口的实现类*/
        String time= new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date());/*获取当前时间*/
        if(categoryDao.addCategory(new Category(name,time,user.getAccount(),intro))){
            System.out.println("用户添加分类成功");
            try {
                request.getSession().setAttribute("userCategories",categoryDao.getCategories(user));/*更新集合*/
            } catch (SQLException sqlException) {
                sqlException.printStackTrace();
            }
        }else{
            System.out.println("用户添加分类失败");
        }
    }
}
